package cn.wolfcode.crm.service.impl;


import cn.wolfcode.crm.domain.*;
import cn.wolfcode.crm.mapper.*;
import cn.wolfcode.crm.query.ObjectQuery;
import cn.wolfcode.crm.query.PageResult;
import cn.wolfcode.crm.service.IChargeQueryService;
import cn.wolfcode.crm.service.IInsurancebillService;
import cn.wolfcode.crm.util.CRMConstant;
import com.alibaba.druid.util.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class InsurancebillServiceImpl implements IInsurancebillService {


    @Autowired
    private InsurancebillMapper insurancebillMapper;

    @Autowired
    private ClientMapper clientMapper;

    @Autowired
    private CarMapper carMapper;

    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private SaleAccountMapper saleAccountMapper;

    @Autowired
    private IChargeQueryService chargeQueryService;

    public void save(Insurancebill insurancebill) {

        //如果是从客户资源表中查询出来 的客户 就不必要 在添加进客户表
        if (insurancebill.getApplicant().getId() == null) {
            insurancebill.getApplicant().setState(CRMConstant.Insurancebill.STATE_TEMP);
            insurancebill.getApplicant().setInputUser((Employee) SecurityUtils.getSubject().getPrincipal());
            insurancebill.getApplicant().setInputTime(new Date());
            clientMapper.insert(insurancebill.getApplicant());
        }
        //每辆车的信息  录入表  方便我们查询
        carMapper.insert(insurancebill.getCar());
        insurancebill.setInputUser((Employee) SecurityUtils.getSubject().getPrincipal());
        insurancebill.setVdate(new Date());
        insurancebill.setState(CRMConstant.Insurancebill.STATE_TEMP);
        //根据时间生成单号
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        insurancebill.setOddNumber(sdf.format(new Date()));
        //添加完 投保单 在维护保单与产品的关系
        insurancebillMapper.insert(insurancebill);
        if (insurancebill.getProductIds() != null) {
            for (Long productId : insurancebill.getProductIds()) {
                insurancebillMapper.saveBillProductRelation(insurancebill.getId(), productId);
                System.out.println(productId);
            }
        }
    }

    public void delete(Long id) {
        insurancebillMapper.deleteByPrimaryKey(id);

    }

    public void update(Insurancebill insurancebill) {
        if (insurancebill.getId() == null) {
            return;
        }
        //更新车的信息
        carMapper.updateByPrimaryKey(insurancebill.getCar());
        //车编号未改变,不处理保险单车编号等
        for (Long id : insurancebill.getProductIds()) {
            System.out.println(id);
        }
        insurancebillMapper.deleteBillProductRelation(insurancebill.getId());
        if (insurancebill.getProductIds() != null) {
            for (Long productId : insurancebill.getProductIds()) {
                insurancebillMapper.saveBillProductRelation(insurancebill.getId(), productId);
            }
        }
        insurancebillMapper.updateTempOddByInsuranceBillId(insurancebill);
    }

    public Insurancebill get(Long id) {
        return insurancebillMapper.selectByPrimaryKey(id);
    }

    public List<Insurancebill> getAll() {

        return insurancebillMapper.selectAll();
    }

    public PageResult<Insurancebill> query(ObjectQuery qo) {
        //qo.setState(CRMConstant.Insurancebill.STATE_TEMP);
        int totalCount = insurancebillMapper.queryForCount(qo);
        if (totalCount == 0) {
            return new PageResult<Insurancebill>(totalCount, Collections.<Insurancebill>emptyList());
        }
        return new PageResult<Insurancebill>(totalCount, insurancebillMapper.queryForList(qo));
    }

    public void changState(Long billId, int state, String info) {
        insurancebillMapper.changState(billId, state);
        if (state == CRMConstant.Insurancebill.STATE_REJECT || state == CRMConstant.Insurancebill.STATE_WAIT_PAY
                || state == CRMConstant.Insurancebill.STATE_CORRECT) {
            Insurancebill insurancebill = new Insurancebill();
            insurancebill.setAuditUser((Employee) SecurityUtils.getSubject().getPrincipal());
            insurancebill.setAuditDate(new Date());
            insurancebill.setId(billId);
            insurancebill.setInfo(StringUtils.isEmpty(info) ? null : info);
            insurancebillMapper.updateAduitIdAndAduitTime(insurancebill);
        }
    }

    //根据客户的id查询该客户对应的已经进行过赔付的保险单据
    public List<Insurancebill> checkWhichCompensate(Long id) {
        List<Insurancebill> bills =
                insurancebillMapper.checkWhichCompensate(id, CRMConstant.Insurancebill.STATE_COMPENSATE);
        return bills;
    }

    @Override
    public void updateDate(Insurancebill bill) {
        insurancebillMapper.updateByPrimaryKey(bill);
    }

    @Override
    public void pay(Insurancebill bill) {
        int limitYear = bill.getLimitYear();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(bill.getBeginDate());
        calendar.add(Calendar.YEAR, limitYear);
        Date endDate = calendar.getTime();
        bill.setEndDate(endDate);
        bill.getApplicant().setState(CRMConstant.Client.STATE_FORMAL);
        bill.setState(CRMConstant.Insurancebill.STATE_ISSUE);
        insurancebillMapper.updateByPrimaryKey(bill);
        clientMapper.changeClientState(bill.getApplicant());

        Insurancebill insurancebill = insurancebillMapper.selectByPrimaryKey(bill.getId());
        //添加报表数据
        List<Product> list = productMapper.queryProductByBillId(bill.getId());
        for (Product pro : list) {
            SaleAccount saleAccount = new SaleAccount();
            saleAccount.setAmount(pro.getAnnualfee().multiply(new BigDecimal(insurancebill.getLimitYear())));
            saleAccount.setEmployeeId(insurancebill.getInputUser().getId());
            saleAccount.setOrganizationId(insurancebill.getOrganization().getId());
            saleAccount.setVdate(insurancebill.getVdate());
            saleAccount.setProductId(pro.getId());
            saleAccountMapper.insert(saleAccount);
            System.out.println(pro.getId());
        }
        ChargeQuery chargeQuery = new ChargeQuery();
        chargeQuery.setApplicant(insurancebill.getApplicant());
        chargeQuery.setBeginDate(insurancebill.getBeginDate());
        chargeQuery.setPremium(insurancebill.getTotalPrice());
        chargeQuery.setBill(insurancebill);
        chargeQuery.setLimitYear(insurancebill.getLimitYear());
        chargeQuery.setEndDate(insurancebill.getEndDate());
        chargeQuery.setDictionary(insurancebill.getDictionary());
        chargeQuery.setOrganization(insurancebill.getOrganization());
        chargeQuery.setInputUser(insurancebill.getInputUser());
        chargeQueryService.save(chargeQuery);
    }


    //销售总额,成功缴费
    public BigDecimal selectBillAccount() {
        BigDecimal account = insurancebillMapper.selectBillAccount();
        if (account == null) {
            return BigDecimal.ZERO;
        }
        return account;
    }

}
